import requests
import traceback
import time
import random
import threading
import base64

HAS_USED =[]
lock = threading.Lock()


def get_ips(proxy_id: str, key, un_key):
    result = []
    try:
        res = requests.get(f'https://syproxy.datatell.com.cn/getProxy?id={proxy_id}', timeout=20)
        ips = res.json().get("ips")
        now = int(time.time() * 1000)
        for data in ips:
            expire_timestamp = data['expire_timestamp']
            ip = data['ip']
            expire = expire_timestamp - now
            address = data['address']
            # print(now, expire_timestamp, expire, ip)
            # 尽量使用中间 前后都不要
            start = 8 * 60 * 1000
            end = 50 * 60 * 1000
            if 'linode_goo' in proxy_id:
                start = 60 * 60 * 1000
                end = 180 * 60 * 1000

            if start < expire < end:
                # print(key, address, un_key)
                if key in address and un_key not in address:
                    result.append(ip)
    except Exception as e:
        print("get_ips failed , try again !", str(e))
        traceback.print_exc()
    return result


def gen_ssr_link(ip, port, password='XUIMVT5vacNoMZY6'):
    method = 'chacha20-ietf'
    protocol = 'origin'
    obfs = 'plain'
    password = base64.urlsafe_b64encode(password.encode('utf-8')).decode('utf-8').rstrip('=')
    remarks = base64.urlsafe_b64encode(ip.encode('utf-8')).decode('utf-8').rstrip('=')
    group = base64.urlsafe_b64encode('pppoe'.encode('utf-8')).decode('utf-8').rstrip('=')
    ssr = 'ssr://' + base64.urlsafe_b64encode(
        f'{ip}:{port}:{protocol}:{method}:{obfs}:{password}/?remarks={remarks}&group={group}'.encode(
            'utf-8')).decode('utf-8').rstrip('=')
    # print('Gen ssr link:', ssr)
    return ssr


def to_proxies(ips, ports, password):
    proxies = []
    for ip in ips:
        for port in ports:
            proxy = gen_ssr_link(ip, port, password)
            proxies.append(proxy)

    return proxies


def proxy(proxy_id: str, key, un_key, ports, password):
    print(proxy_id, key, un_key, ports, password)
    with lock:  # 获取锁
        ips = get_ips(proxy_id, key, un_key)
        proxies = to_proxies(ips, ports, password)
        if len(proxies):
            no_uses = list(set(proxies) - set(HAS_USED))
            uses = list(set(proxies) & set(HAS_USED))

            if len(no_uses):
                proxy = random.choice(no_uses)
                HAS_USED.clear()
                HAS_USED.extend(uses)
                HAS_USED.append(proxy)
                return proxy
            else:
                print("----all oracle ip used----")
        print("---- oracle ip bad ----")
    return None


if __name__ == '__main__':
    # for _ in range(20):
    #     print(proxy('ss-oracle', '', 'v2', ['50001', '50002'], 'shuyuan008'))
    print(gen_ssr_link("108.165.145.161", 55001))

